import debounce from "@/utils/debounce";
import { onMounted, onUnmounted, ref } from "vue";
// #ifdef H5
import Speech from "@/utils/speech";
// #endif
// #ifdef MP-WEIXIN
const plugin = requirePlugin("WechatSI");
const recorderManager = plugin.getRecordRecognitionManager();
// #endif

export default function useTouch(onSend: (message: string) => void) {
  const audioPanel = ref<{ open: () => void; close: () => void }>();
  const popupText = ref("");

  const time = ref({
    timer: 0,
    count: 0
  });

  onUnmounted(() => {
    // #ifdef H5
    Speech.instance.off("radio");
    // #endif
  });
  onMounted(() => {
    //  #ifdef MP-WEIXIN
    recorderManager.onRecognize = (res: any) => {
      console.log("stop", res);
      // popupText.value += res.result;
    };
    recorderManager.onStop = (res: any) => {
      console.log("stop", res);
      const text = res.result;
      if (!text) {
        uni.showToast({
          title: "没有听到你的声音呢",
          icon: "none"
        });
        return;
      }
      if (text) {
        onSend?.(text);
      }
    };
    // #endif
    // #ifdef H5
    Speech.instance.on("radio", (e: string) => {
      if (e) {
        popupText.value += e;
        if (time.value.timer) {
          clearTimeout(time.value.timer);
        }
      } else {
        uni.showToast({
          title: "未识别到语音",
          icon: "none"
        });
        cancel();
      }
    });
    // #endif
  });

  function timeout() {
    time.value.timer = setTimeout(() => {
      time.value.count += 1;
      timeout();
    }, 1000);
  }

  function checkText(text: string) {
    if (!text) {
      uni.showToast({
        title: "没有听到你的声音呢",
        icon: "none"
      });
    }

    if (time.value.count <= 1) {
      uni.showToast({
        title: "录音时间太短",
        icon: "none"
      });
    }
    if (text) {
      onSend?.(text);
    }
  }
  const start = debounce((e: any) => {
    e.preventDefault();
    e.stopPropagation();

    popupText.value = "";
    audioPanel.value?.open();

    // #ifdef MP-WEIXIN
    recorderManager.start({
      duration: 60000,
      lang: "zh_CN"
    });
    // #endif

    // #ifdef H5
    if (Speech.instance.creating) {
      return;
    }
    if (time.value.timer) {
      clearTimeout(time.value.timer);
    }
    Speech.instance.start();
    // #endif

    timeout();
  });

  const end = debounce(() => {
    // #ifdef H5
    const text = popupText.value.trim();
    checkText(text);
    // #endif
    cancel();
  });

  const cancel = () => {
    audioPanel.value?.close();

    popupText.value = "";
    time.value.count = 0;
    if (time.value.timer) {
      clearTimeout(time.value.timer);
    }
    // #ifdef MP-WEIXIN
    recorderManager.stop();
    // #endif
    // #ifdef H5
    Speech.instance.stop();
    // #endif
  };

  return { time, popupText, audioPanel, start, end, cancel };
}
